package com.winit.openapi.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.oms.spi.isp.ISPOrderRevenueService;
import com.winit.oms.spi.isp.ISPOrderService;
import com.winit.oms.spi.isp.command.transaction.OrderRevenueQueryCommand;
import com.winit.oms.spi.isp.vo.ISPOrder;
import com.winit.oms.spi.isp.vo.ISPOrderLine;
import com.winit.oms.spi.vo.OrderRevenue;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * 用户交易记录
 * 
 * @version Revision History
 * 
 * <pre>
 * Author     Version       Date        Changes
 * long.yue    1.0           2015年1月8日     Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/userTransaction")
public class UserTransactionController extends BaseController {

    @Autowired
    private ISPOrderRevenueService iSPOrderRevenueService;

    @Autowired
    private ISPOrderService        ispOrderService;

    /**
     * ISP交易记录
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/ispOrderList")
    public String transactionList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = (JSONObject) requestMsg.getData();
        OrderRevenueQueryCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validSearchISPOrder(json);
            command = buildSearchOrderCommand(json);
            command.setCtx(CommandContext.getContext());
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Page<OrderRevenue> orderPage = iSPOrderRevenueService.queryRevenuePage(command);
        List<OrderRevenue> revenueList = orderPage.getContent();
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        reBuildTransList(dataList, revenueList);
        Map<String, Object> pageMap = new HashMap<String, Object>();
        pageMap.put("pageNo", orderPage.getPageable().getPageNumber());
        pageMap.put("pageSize", orderPage.getPageable().getPageSize());
        pageMap.put("totalCount", orderPage.getTotalElements());
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", dataList);
        data.put("pageParams", pageMap);
        responseMsg.setData(data);

        return SUCCESS;
    }

    private void validSearchISPOrder(JSONObject json) {
        // orderNo
        ValidateUtil.validMaxLength(json, "orderNo", 60);
        // refNo
        ValidateUtil.validMaxLength(json, "refNo", 60);
        // buyerName
        ValidateUtil.validMaxLength(json, "buyerName", 50);
        // winitPorductID【Bug : 前端传的是winitPorductID，名字错误，且传的值实际是winitProductCode】
//        ValidateUtil.validInteger(json, "winitPorductID");
        // status
        ValidateUtil.validMaxLength(json, "status", 20);
        // orderDateStart
        ValidateUtil.validDateString(json, "orderDateStart", DateUtil.SIMPLE_DATE_STRING);
        // orderDateEnd
        ValidateUtil.validDateString(json, "orderDateEnd", DateUtil.SIMPLE_DATE_STRING);

        // pageParams
        if (json.containsKey("pageParams")) {
            Object obj = json.get("pageParams");
            if (obj instanceof JSONObject) {
                JSONObject pageParams = (JSONObject) obj;
                // pageNo
                ValidateUtil.validInteger(pageParams, "pageNo");
                // pageSize
                ValidateUtil.validInteger(pageParams, "pageSize");

                if (pageParams.containsKey("pageNo")) {
                    int pageNo = pageParams.getInteger("pageNo");
                    if (pageNo < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                    }
                }
                if (pageParams.containsKey("pageSize")) {
                    int pageSize = pageParams.getInteger("pageSize");
                    if (pageSize < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                    }
                }
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
            }
        }
    }

    private OrderRevenueQueryCommand buildSearchOrderCommand(JSONObject json) {
        OrderRevenueQueryCommand command = new OrderRevenueQueryCommand();
        Searchable search = Searchable.newSearchable();
        Bpartner bp = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        search.addSearchFilter("BPARTNER_ID", SearchOperator.eq, bp.getcBpartnerId().intValue());
        search.addSearchFilter("STATUS", SearchOperator.eq, ApiConstant.STATUS_SUCCESS);
        if (json.containsKey("orderNo")) {
            search.addSearchFilter("ORDER_NO", SearchOperator.eq, json.getString("orderNo"));
        }
        if (json.containsKey("refNo")) {
            search.addSearchFilter("REF_NO", SearchOperator.eq, json.getString("refNo"));
        }
        // winitPorductID
        if (json.containsKey("winitPorductID")) {
            search.addSearchFilter("WINIT_PRODUCT_CODE", SearchOperator.eq, json.getString("winitPorductID"));
        }
        // orderDateStart
        if (json.containsKey("orderDateStart")) {
        	 String orderDateStart = json.getString("orderDateStart");
             orderDateStart += " 00:00:00";
             Date orderDatestart = DateUtil.parse2Date(orderDateStart, DateUtil.FULL_DATE_STRING); 
             command.setOrderDateStart(orderDatestart);
        }
        // orderDateEnd
        if (json.containsKey("orderDateEnd")) { 
            String orderDateEnd = json.getString("orderDateEnd");
            orderDateEnd += " 23:59:59";
            Date toDate = DateUtil.parse2Date(orderDateEnd, DateUtil.FULL_DATE_STRING); 
            command.setOrderDateEnd(toDate);
        }
        
        // 费用大于0
        search.addSearchFilter("AMOUNT", SearchOperator.gt, 0);

        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (json.containsKey("pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");
            // pageNo
            if (pageParams.containsKey("pageNo")) {
                pageNo = pageParams.getInteger("pageNo");
            }
            // pageSize
            if (pageParams.containsKey("pageSize")) {
                pageSize = pageParams.getInteger("pageSize");
            }
        }
        search.setPage(pageNo, pageSize);
        command.setSearchable(search);
        return command;
    }

    private void reBuildTransList(List<Map<String, Object>> dataList, List<OrderRevenue> revenueList) {

        for (int i = 0; i < revenueList.size(); i++) {
            OrderRevenue revenue = revenueList.get(i);
            GetByKeyCommand<String> command = new GetByKeyCommand<String>();
            command.setCtx(CommandContext.getContext());
            command.setSearchKey(revenue.getOrderNo());
            ISPOrder order = this.ispOrderService.getISPOrderByNo(command);
            Map<String, Object> r1 = reBuildISPOrder(order, revenue);
            dataList.add(r1);
        }
    }

    private Map<String, Object> reBuildISPOrder(ISPOrder order, OrderRevenue revenue) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderNo", order.getOrderNo());
        map.put("winitProductName", order.getWinitProductName());
        map.put("refNo", order.getSellerOrderNo());
        map.put("buyerName", order.getBuyerFullname());
        map.put("orderDate", DateUtil.parse2String(order.getOrderDate(), DateUtil.FULL_DATE_STRING));
        map.put("transactionDate", DateUtil.parse2String(revenue.getAcctDate(), DateUtil.FULL_DATE_STRING));
        map.put("deliveryFee", revenue.getAmount());
        map.put("chargeName", revenue.getChargeName());//添加费用名称        
        List<ISPOrderLine> orderLineList = order.getOrderLineList();
        map.put("packageDesc", orderLineList.get(0).getDescription());
        map.put("length", orderLineList.get(0).getCfmLength());
        map.put("width", orderLineList.get(0).getCfmWidth());
        map.put("height", orderLineList.get(0).getCfmHeight());
        map.put("weight", orderLineList.get(0).getCfmGrossWeight());
        //原币币种
        map.put("currencyCode", revenue.getCurrencyCode());
        return map;
    }
}
